<script setup lang="ts">
import { ref, defineProps, computed, nextTick } from 'vue'
import unpaidImg from '#/assets/images/pay/unpaid.png'
import payingImg from '#/assets/images/pay/paying.png'
import completedImg from '#/assets/images/pay/completed.png'
import submitOrderPayingImg from '#/assets/images/pay/sumbit_order_paying.png'
import submitOrderCompletedImg from '#/assets/images/pay/sumbit_order_completed.png'
import {
  SUBMIT_ORDER, PAY_ORDER, COMPLETE_ORDER, PAY_STATUS_UNPAID, PAY_STATUS_PAYING,
  PAY_STATUS_COMPLETED, type PayStep
} from './const'
import SubmitOrder from './submit-order.vue'
import PayOrder from './pay-order.vue'
import CompleteOrder from './complete-order.vue'
import { getCertOrderApi } from '#/api/lesson/pay'
import { useUserStore } from '@vben/stores';
import { useRoute } from 'vue-router'
import { createUserCertOrderApi } from '#/api/lesson/pay'

const route = useRoute()
const certificationId = ref(route.params.id as string)
const userStore = useUserStore();

const orderRef = ref<any>(null)
const loading = ref(false)
defineOptions({ name: 'DialogPay' })
const props = defineProps<{
  visible: boolean
}>()
const emit = defineEmits(['update:visible'])
const orderInfo = ref<any>({})
const sumbitLoading = ref(false)
const isSubmitOrder = ref(false)

const initPaySteps = (): PayStep[] => {
  return [
    { name: '提交订单', key: SUBMIT_ORDER, status: PAY_STATUS_PAYING, payStatus: false },
    { name: '支付订单', key: PAY_ORDER, status: PAY_STATUS_UNPAID, payStatus: false },
    { name: '完成支付', key: COMPLETE_ORDER, status: PAY_STATUS_UNPAID, payStatus: true }
  ]
}
const currentStepIndex = ref(0)
const componentMap: Record<string, any> = {
  [SUBMIT_ORDER]: SubmitOrder,
  [PAY_ORDER]: PayOrder,
  [COMPLETE_ORDER]: CompleteOrder
}

const currentStepKey = computed(() => {
  return paySteps.value[currentStepIndex.value]!.key
})

const currentStep = computed(() => {
  return componentMap[currentStepKey.value]
})
// 定义支付流程的三个状态队列
const paySteps = ref<PayStep[]>(initPaySteps())
const statusBgMap: Record<string, string> = {
  [PAY_STATUS_UNPAID]: unpaidImg,
  [PAY_STATUS_PAYING]: payingImg,
  [PAY_STATUS_COMPLETED]: completedImg,
}
const getBgByStatus = (step: PayStep) => {
  if (step.key === SUBMIT_ORDER) {
    if (step.status === PAY_STATUS_PAYING) {
      return `url(${submitOrderPayingImg})`
    } else {
      return `url(${submitOrderCompletedImg})`
    }
  } else {
    return `url(${statusBgMap[step.status]})`
  }
}

// 获取文字颜色
const getTextColor = (status: string) => {
  return status === PAY_STATUS_PAYING ? '#0067d1' : '#595959'
}
const visible = computed({
  get() {
    if (props.visible) {
      getCertOrder()
    }
    return props.visible
  },
  set(value) {
    if (!value) {
      orderRef.value?.stopPollingPayResult?.()
    }
    emit('update:visible', value)
  }
})

const nextStep = (step?: number) => {
  if (currentStepIndex.value < paySteps.value.length - 1) {
    // 将当前步骤设为已完成
    paySteps.value[currentStepIndex.value]!.status = PAY_STATUS_COMPLETED
    if (step) {
      currentStepIndex.value = step
      if (step == 0) {
        paySteps.value = initPaySteps()
        return;
      }
    } else {
      // 将下一步骤设为支付中
      currentStepIndex.value++
    }

    if (currentStepIndex.value === paySteps.value.length - 1) {
      paySteps.value[currentStepIndex.value]!.status = PAY_STATUS_COMPLETED
    }
    paySteps.value[currentStepIndex.value]!.status = PAY_STATUS_PAYING
  }
}

const resetPaySteps = () => {
  paySteps.value = initPaySteps()
  currentStepIndex.value = 0
}

const handleClose = () => {
  visible.value = false
  resetPaySteps()
}

const submitOrder = () => {
  sumbitLoading.value = true
  const amount = orderRef.value.getPrice()?.toString()
  createUserCertOrderApi({
    userId: userStore.userInfo?.userId as string,
    certificateId: certificationId.value,
    buyMethod: 'per_time',
    quantity: Number(orderRef.value.getQuantity()),
    amount
  }).then(res => {
    orderInfo.value = { ...res, amount }
    nextStep()
  }).finally(() => {
    sumbitLoading.value = false
  })
}

const getCertOrder = async () => {
  loading.value = true
  const res = await getCertOrderApi(userStore.userInfo?.userId as string, certificationId.value)
  loading.value = false
  if (res) {
    orderInfo.value = res
    nextTick(() => {
      nextStep()
    })
  }
}

</script>

<template>
  <el-dialog v-model="visible" draggable title="购买认证" :close-on-click-modal="false" :destroy-on-close="true"
    width="1000px" @close="handleClose">
    <div class="flex items-center">
      <div v-for="item in paySteps" :key="item.key"
        class="flex-1 h-10 bg-no-repeat bg-contain bg-center flex items-center justify-center" :style="{
          backgroundImage: getBgByStatus(item),
          color: getTextColor(item.status)
        }">
        <span class="text-sm">{{ paySteps.indexOf(item) + 1 }}.{{ item.name }}</span>
      </div>
    </div>

    <component v-loading="loading" :visible="props.visible" :loading="loading" ref="orderRef" @close="handleClose" :orderInfo="orderInfo"
      @nextStep="nextStep" :is="currentStep" v-if="currentStep" :key="currentStep" class="pb-3 pt-6 min-h-[410px]"
      :steps="paySteps[currentStepIndex]" @isSubmitOrder="isSubmitOrder = $event" />

    <template #footer>
      <div class="flex items-center justify-center">
        <!-- <el-button type="primary" @click="resetPaySteps">重新开始</el-button>
        <el-button type="primary" @click="nextStep">下一步</el-button> -->
      </div>
      <!-- 提交订单 -->
      <div v-if="currentStepKey === SUBMIT_ORDER">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="submitOrder" :disabled="isSubmitOrder" :loading="sumbitLoading">提交订单</el-button>
      </div>
      <!-- 完成订单 -->
      <div v-if="currentStepKey === COMPLETE_ORDER">
        <el-button type="primary" @click="handleClose">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped></style>
